<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 2017/9/5
 * Time: 17:07
 */

namespace app\admin\model;


class MenuModel extends BaseModel
{

    protected $table = 'app_auth_rule';
    protected $pk = 'id';

    /**
     * 根据权限获取顶级菜单，pid为0
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getTopMenu() {
        $rules = new AuthGroupAccessModel();

        if (session('user_info')['id'] == 1) {
            $result = $this->where(array('pid' => '0', 'status' => parent::NORMAL_STATUS))->select();
        } else {
            $result = $rules->getUserRules(session('user_info')['id'], '0');
        }

        //show_bug($result);
        return $result;
    }

    /**
     * 根据权限左边导航菜单
     * @param $pid 父id
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getSubMenu($pid) {

        $rules = new AuthGroupAccessModel();


        if (session('user_info')['id'] == 1) {
            $result = $this->where(array('pid' => $pid, 'status' => parent::NORMAL_STATUS))->select();
        } else {
            $result = $rules->getUserRules(session('user_info')['id'], $pid);
        }

        //组装左边菜单列表
        foreach ($result as $key => $val) {
            $result[$key]['spread'] = false;
            if (session('user_info')['id'] == 1) {
                $res = $this->where(array('pid' => $val['id'], 'status' => parent::NORMAL_STATUS))->select();
            } else {
                $res = $rules->getUserRules(session('user_info')['id'], $val['id']);
            }

            //生成URL
            foreach ($res as $k => $v) {
                $url = url($v['url']);
                $res[$k]['url'] = $url;
            }

            $result[$key]['children'] = $res;
        }

        return $result;
        /*$demo = '[{"title": "资讯管理","icon": "&#x1002;","spread": false,"children":
                    [{"title": "资讯列表","icon": "fa-check-square-o","href": "information.html"},
                     {"title": "资讯分类","icon": "fa-check-square-o","href": "category.html"}]
                }]';
        return $demo;*/
    }

    /**
     * @description:显示菜单
     * @param unknown $num
     * @return multitype:unknown string
     */
    public function selectAllMenu($type = 1) {
        $where = array(
            //'status' => parent::NORMAL_STATUS,
            //'is_menu' => 1,
        );

        if ($type == 2) {
            unset($where['is_menu']);
        }

        return $this->where($where)->select();


    }

    /**
     * 菜单列表数据列处理
     * @return false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getMenuWithLine(){
        $arr_menu = $this->where(array("level"=>array("gt","0")))->order("l")->select();
        $arr_prefix=array();
        $arr_parent=array();
        foreach ($arr_menu as &$m) {
            //以下代码很吐血
            $line="";
            $parent=end($arr_parent);//取得当前分类菜单
            //当有分类菜单时
            if($parent){
                $level_d=$parent["level"]-$m["level"];//当前菜单跟分类菜单的层次差
                //当层次差大于等于0时，说明当前菜单跟当前分类菜单没有父子关系
                if($level_d>=0){
                    //对应层次差从数组弹出对应数量的元素
                    for($i=0;$i<$level_d+1;$i++){
                        array_pop($arr_prefix);
                        array_pop($arr_parent);
                    }
                    $parent=end($arr_parent);//重新取当前分类菜单
                }
                $is_level_end=$parent["r"]-$m["r"]===1?true:false;//当前菜单是否是本层次最后一个
            }
            //当有分类菜单时，说明当前菜单是子菜单，需加线
            if($parent){
                //当前菜单是分类中最后一个菜单时
                if($is_level_end){
                    $line="└─";
                }else{
                    $line="├─";
                }
                $m["line"]=implode("",$arr_prefix)."&nbsp;".$line;
            }else{
                $m["line"]="";
            }

            $has_sub=$m["r"]-$m["l"]>1?true:false;
            //当前菜单有子菜单时
            if($has_sub){
                //将当前分类压入栈
                array_push($arr_parent,$m);
                //当前菜单是子菜单时，需加前缀
                if($parent){
                    //当前菜单是分类中最后一个菜单时
                    if($is_level_end){
                        array_push($arr_prefix,"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                    }else{
                        array_push($arr_prefix,"&nbsp;│&nbsp;&nbsp;&nbsp;&nbsp;");
                    }
                }
            }
        }
        return $arr_menu;
    }

    /**
     * @description:添加菜单
     * @param unknown $data
     */
    public function addAdminMenu($data) {
        $menu_info = array(
            'url' => $data['url'] ? $data['url'] : '#',
            'icon' => $data['menuIcon'],
            'title' => $data['menuName'],
            'pid' => $data['pid'] ? $data['pid'] : 0,
            'is_menu' => $data['is_menu'],
            'type' => 1,
        );
        //show_bug($menu_info);die;
        return $this->insert($menu_info);
    }

    /*
       根据传入的父节点 id ，在父节点的子节点最后的位置新增一个新节点
    */
    public function add($dataInfo){
        $parent_id = $dataInfo['pid'];
        $menu_name = $dataInfo['menuName'];
        $this->startTrans();

        //获取父节点信息
        $parent_menu=$this->field("r,level,pid")->where(array("id"=>$parent_id))->find();
        $data = ["title"=>$menu_name];
        //show_bug($parent_menu);
        //根据父节点计算出新节点的左右值及level
        $data["l"]=$parent_menu["r"];
        $data["r"]=$parent_menu["r"]+1;
        $data["level"]=$parent_menu["level"]+1;
        $data["pid"]=$parent_menu['pid'];
        $data["url"]=$dataInfo['url'];

        if(false===$this->create($data)) $this->error($this->getError());

        //将受到影响的节点左值加2
        if(false===$this->where(array("l"=>array("gt",$parent_menu["r"])))->setInc("l",2)){
            $this->rollback();
            $this->error($this->getError());
        }
        //将受到影响的节点右值加2
        if(false===$this->where(array("r"=>array("egt",$parent_menu["r"])))->setInc("r",2)){
            $this->rollback();
            $this->error($this->getError());
        }
        if(false===$this->save()) {
            $this->rollback();
            $this->error($this->getError());
        }
        $this->commit();
        return true;

    }

    /**
     * @description:查询是否已存在的opt
     */
    public function isExistOpt($url, $id = null) {
        $where = array(
            'url' => $url,
            'status' => parent::NORMAL_STATUS,

        );
        if ($id) {
            $where['id'] = array('neq', $id);
        }
        return $this->where($where)->find();
    }

    /**
     * @description:是否为二级菜单
     */
    public function isSecondaryMenu($id) {
        $where = array(
            'id' => $id,
        );
        $pid = $this->where($where)->value('pid');
        if($pid){
            $pid2 = $this->where(array('id' => $pid))->value('pid');
            if($pid2){
                $pid3 = $this->where(array('id' => $pid2))->value('pid');
                if($pid3){
                    return false;
                }else{
                    return true;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }

        //return $this->where($where)->value('pid') ? true : false;
    }

    /**
     * @description:编辑菜单
     */
    public function editAdminMenu($data) {

        $where = array(
            'id' => $data['id'],
        );

        $menu_info = array(
            'url' => $data['url'] ? $data['url']  : '',
            'icon' => $data['menuIcon'],
            'title' => $data['menuName'],
        );

        unset($data['id']);

        return $this->where($where)->update($menu_info);
    }

    /**
     * @description:是否存在子菜单
     */
    public function isExistSonMenu($id) {
        $where = array(
            'pid' => $id,
            'status' => parent::NORMAL_STATUS,
        );

        return $this->where($where)->find();
    }

    /**
     * @description:删除菜单
     * @param unknown $id
     */
    public function deleteAdminMenu($id) {

        return $this->where('id',$id)->delete();
    }

    /**
     * @description:根据id查询菜单信息
     * @param unknown $id
     * @return \Think\mixed
     */
    public function selectMenuById($id) {
        $where = array(
            'id' => $id,
        );

        return $this->where($where)->find();
    }

    /**
     * @description:查询三级菜单
     * @param unknown $id
     * @return \Think\mixed
     */
    public function selectOpt($id) {
        $where = array(
            'pid' => $id,
            'status' => parent::NORMAL_STATUS,
        );

        return $this->where($where)->select();

    }

    /**
     * 根据规则id数组获取菜单
     * @param unknown $rules_arr
     */
    public function getMenus($rules_arr, $pid = 0, $is_menu = 1) {
        $where = array(
            'id' => array('in', $rules_arr),
            'is_menu' => 1,
            'status' => 1,
        );
        if ($pid) $where['pid'] = $pid;

        return $this->where($where)->select();
    }

    /**
     * @description:查询菜单信息
     * @param unknown $name
     */
    public function selectMenuInfoByName($name) {
        $where = array(
            'menu_name' => $name,
            'status' => parent::NORMAL_STATUS,
        );

        return $this->where($where)->find();
    }

}